<template>
    <div v-loading="loading" class="add">
        <SavePage :title="id ? '编辑合同' : '新增合同'">
            <!-- 审批显示操作按钮 -->
            <template slot="buttons">
                <BaseButton :loading="submitLoading"  :disabled="submitDisabled" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <BaseForm2
                    ref="form"
                    label-position="right"
                    label-width="120px"
                    :fields="fields"
                    :text-model="textModel"
                    :data="form"
                    size="medium"
                    @updateValue="updateEvent"
                ></BaseForm2>
                <CompensateTable ref="compensateTable" :data="tableList"></CompensateTable>
                <TitleTips title="合同附件" />
                <FileUpload
                    ref="fileUpload"
                    :list="form.filesUrl"
                    :tips="fileTips"
                    :accept="accept"
                    :file-rule-type="fileRuleType"
                    @load="handleLoad"
                />
            </template>
        </SavePage>
    </div>
</template>

<script>
import { ContractModel } from '@/models'
import BaseForm2 from '@/components/BaseForm2'
import CompensateTable from './CompensateTable'

export default {
    name: 'PlanAdd',
    components: {
        BaseForm2,
        CompensateTable
    },
    data() {
        return {
            model: new ContractModel(),
            loading: false,
            submitDisabled: false,
            submitLoading: false,
            id: '',
            type: 'add',
            textModel: false,
            form: {
                code: '',
                name: '',
                projectName: '',
                section: '',
                employerId: '',
                contractorId: '',
                contractDate: '',
                date: '',
                maintProject: '',
                filesUrl: []
            },
            fields: [
                {
                    label: '基础信息',
                    children: [
                        {
                            key: 'code',
                            label: '合同编号',
                            type: 'input',
                            placeholder: '请输入',
                            maxlength: '20',
                            'show-word-limit': true,
                            span: 8,
                            rules: [
                                { required: true, message: '必填项', trigger: ['change'] },
                                { validator: this.validCodeUnique, trigger: ['blur'] }
                            ]
                        },
                        {
                            key: 'name',
                            label: '合同名称',
                            type: 'input',
                            placeholder: '请输入',
                            span: 8,
                            maxlength: '100',
                            'show-word-limit': true,
                            rules: [
                                { required: true, message: '必填项', trigger: ['blur'] },
                                { validator: this.validNameUnique, trigger: ['blur'] }
                            ]
                        },
                        {
                            key: 'projectName',
                            label: '项目名称',
                            type: 'input',
                            placeholder: '请输入',
                            span: 8,
                            maxlength: '100',
                            'show-word-limit': true,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'section',
                            label: '标段',
                            type: 'input',
                            placeholder: '请输入',
                            span: 8,
                            maxlength: '20',
                            'show-word-limit': true
                        },
                        {
                            options: [],
                            key: 'employerId',
                            label: '发包人',
                            type: 'normal-select',
                            defaultValue: '',
                            placeholder: '请选择',
                            disableDefault: true,
                            span: 8,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            options: [],
                            key: 'contractorId',
                            label: '承包人',
                            type: 'normal-select',
                            placeholder: '请选择',
                            span: 8,
                            filterable: true,
                            showText: true,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'contractDate',
                            type: 'date-input',
                            format: 'yyyy-MM-dd',
                            'value-format': 'yyyy-MM-dd',
                            span: 8,
                            label: '合同签订日期',
                            placeholder: '请选择',
                            rules: [
                                { required: true, message: '必填项', trigger: ['change'] }
                            ]
                        },
                        {
                            key: 'date',
                            type: 'date-range-input',
                            format: 'yyyy-MM-dd',
                            'value-format': 'yyyy-MM-dd',
                            span: 8,
                            label: '工期',
                            'start-placeholder': '开始日期',
                            'end-placeholder': '结束日期',
                            rules: [
                                { required: true, message: '必填项', trigger: ['change'] }
                            ]
                        },
                        {
                            key: 'maintProject',
                            type: 'textarea',
                            label: '养护项目',
                            resize: 'vertical',
                            class: 'text-overflow',
                            placeholder: '请输入',
                            rows: 4,
                            span: 16,
                            maxlength: '200',
                            'show-word-limit': true,
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        }
                    ]
                }
            ],
            tableList: [],
            isCopy: false,
            accept: 'application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/jpeg,image/png',
            fileRuleType: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png'],
            fileTips: '最多上传9个文件，单个文件最多50M，支持：.pdf .doc .docx  .xls .xlsx .jpg .jpeg .png 格式。'
        }
    },
    created() {
        this.getQuery()
        this.id && this.getDetail()
        this.getContractorList1()
        this.getContractorList2()
    },
    methods: {
        updateEvent(data) {
            if (data.employerId) {
                if (this.fields[0].children[4].options.length === 0) { return }
                const target = this.fields[0].children[4].options.find(item => item.value === data.employerId)
                this.form.employerName = target.label
            }

            if (data.contractorId) {
                if (this.fields[0].children[5].options.length === 0) { return }
                const target = this.fields[0].children[5].options.find(item => item.value === data.contractorId)
                this.form.contractorName = target.label
            }
        },
        getQuery() {
            this.type = this.$route.query.type
            this.isCopy = this.$route.query.isCopy === 'true'
            console.log(this.$route.query.isCopy)
            if (this.type === 'edit') {
                this.typeName = '编辑'
                this.loading = true
                this.id = this.$route.query.id
            } else {
                this.typeName = '新建'
            }
        },
        validNameUnique(rule, value, callback) {
            this.model.validNameUnique({ name: value, id: this.form.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('合同名称已存在'))
                } else {
                    callback()
                }
            })
        },
        validCodeUnique(rule, value, callback) {
            this.model.validNameUnique({ code: value, id: this.form.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('合同编号已存在'))
                } else {
                    callback()
                }
            })
        },
        handleLoad(value) {
            this.submitDisabled = value
        },
        getContractorList1() {
            this.model.contractorList({type: 1}).then(res => {
                const list = (res || []).map(item => {
                    return {
                        label: item.orgName,
                        value: Number(item.orgId)
                    }
                })
                if (list.length > 0) {
                    this.$set(this.fields[0].children[4], 'options', list)
                    this.$refs.form.updateFormData({ employerId: list[0].value })
                    this.form.employerName = list[0].label
                }
            })
        },
        getContractorList2() {
            this.model.contractorList({type: 2}).then(res => {
                const list = (res || []).map(item => {
                    return {
                        label: item.orgName,
                        value: Number(item.orgId)
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[5], 'options', list)
            })
        },
        getDetail() {
            this.model.detail({ id: this.id }).then(res => {
                this.form = res
                this.tableList = res.maintScopeList || []
                this.form.filesUrl = this.form.filesUrl ? JSON.parse(this.form.filesUrl) : []
                this.form.date = JSON.stringify([this.form.startDate, this.form.endDate])
                // 如果是复制合同，把id删除
                if (this.isCopy) {
                    delete this.form.id
                }
            }).finally(() => {
                this.loading = false
            })
        },
        submit() {
            console.log('this.isCopy>>>', this.isCopy)
            this.submitLoading = true
            this.$refs['form'].validate(async (valid, res) => {
                if (valid) {
                    const validResult = this.$refs['compensateTable'].handleValidate()
                    const filesUrl = JSON.stringify(this.$refs['fileUpload'].getFileList())
                    if (validResult) {
                        const [startDate, endDate] = JSON.parse(res.date)
                        const data = {
                            ...res,
                            [this.isCopy ? 'copyId' : 'id']: this.id,
                            startDate,
                            endDate,
                            // 后端要把名字也传过去
                            employerName: this.form.employerName,
                            contractorName: this.form.contractorName,
                            maintScopeList: this.$refs['compensateTable'].tableList,
                            filesUrl
                        }
                        this.model[this.isCopy ? 'copySave' : 'saveOrUpdate'](data).then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        }).finally(() => {
                            this.submitLoading = false
                        })
                    } else {
                        this.submitLoading = false
                    }
                } else {
                    this.submitLoading = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}

.add {
    width: 100%;
    // padding:0 20px
    .info {
        .sub-title {
            font-size: 14px;
            font-weight: 600;
        }
        .check-box {
            margin-top: 20px;
            .check-list {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                flex-wrap: wrap;
                .check-item {
                    width: 33%;
                    margin: 4px 0;
                }
            }
        }
    }
}
</style>
